package com.boot.stomp.interceptor;

import com.boot.stomp.authentication.StompAuthenticationHandler;
import com.sun.security.auth.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.security.Principal;
import java.util.Objects;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 获取用户登录信息
 * @date 2020/4/27 18:49
 **/
@Deprecated
@Slf4j
//@Component
public class DefaultChannelInterceptor implements ChannelInterceptor {

    private final StompAuthenticationHandler authenticationHandler;

    public DefaultChannelInterceptor() {
        this.authenticationHandler = new StompAuthenticationHandler() {
            @Override
            public Principal getPrincipal(StompHeaderAccessor accessor) {
                String user = accessor.getFirstNativeHeader("user");
                return new UserPrincipal(Objects.requireNonNull(user));
            }

            @Override
            public boolean authentication(Principal principal) {
                return true;
            }
        };
    }

    public DefaultChannelInterceptor(StompAuthenticationHandler authenticationHandler) {
        this.authenticationHandler = authenticationHandler;
    }

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        //1. 判断是否首次连接请求
        assert accessor != null;
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            //2. 验证是否登录
            Principal principal = authenticationHandler.getPrincipal(accessor);
            if (principal == null) {
                log.info("未知用户试图登录");
            } else {
                log.info("用户 {} 试图登录", principal.getName());
                if (authenticationHandler.authentication(principal)) {
                    log.info("验证成功，用户 {} 登录成功", principal.getName());
                    accessor.setUser(principal);
                    return message;
                }
                log.info("验证失败，用户 {} 登录失败", principal.getName());
            }
            return null;
        }
        //不是首次连接，已经成功登陆
        return message;
    }

}
